var express = require('express');
var path = require('path');
var fs = require('fs');
var multipart = require('connect-multiparty');
var router = express.Router();
var Albums = require('../models/albums');


//图片上传
router.post('/uploading',multipart(), function(req, res, next) {  	
	var filename = req.files.img.originalFilename;
	var targetPath = path.resolve('.') + '/public/albumImgs/' + filename;
	fs.createReadStream(req.files.img.path).pipe(fs.createWriteStream(targetPath));
	
	var data = {
		picUrl : 'http://' + req.headers.host + '/albumImgs/' + filename,
	}
	Albums.find({}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			if(doc) {
				data.picId = doc.length + 1;
				Albums.create(data,function(err2, doc2) {
					if(err2) {
						res.json({
							status: "0",
							msg: err2.message
						})
					} else {
						res.json({
							status: "1",
							msg: "",
							result: "success"
						})
					}
				})
			}
		}
	})
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*var data = {
		albumURL : req.body.readAsDataURL
	}
	
 	Albums.find({}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			if(doc) {
				data.albumId = doc.length + 1;
				Albums.create(data,function(err2, doc2) {
					if(err2) {
						res.json({
							status: "0",
							msg: err2.message
						})
					} else {
						res.json({
							status: "1",
							msg: "",
							result: "success"
						})
					}
				})
			}
		}
	})*/
});

//获取图片列表
router.get('/list', function(req, res, next) {  
	let AlbumsModel = Albums.find({}).sort({'picId':-1})
	AlbumsModel.exec({}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			res.json({
				status: "1",
				msg: "",
				result: {
					count: doc.length,
					list: doc
				}
			})
		}
	})
});

//删除图片
router.post('/del', function(req, res, next) {  
	var picId = req.body.picId;
	Albums.remove({picId:picId}, function(err, doc) {
		if(err) {
			res.json({
				status: "0",
				msg: err.message
			})
		} else {
			res.json({
				status:"1",
				msg:"",
				result:"success"
			})
		}
	})
});
module.exports = router;